import os
import json

# 根目录和输出 JSON 路径
root_dir = "/data/nfsroot-vxpp/L2/imacal_vt"
object_list_json = "/data/vxpp_info/L2/object_list_l2.json"
fit_list_dir = "/data/vxpp_info/L2/object_fit_list"

# 确保目标 FITS 列表目录存在
os.makedirs(fit_list_dir, exist_ok=True)

# 目标列表
target_list = []

# 遍历一级子目录（目标名称）
for target in sorted(os.listdir(root_dir)):
    target_path = os.path.join(root_dir, target)
    if not os.path.isdir(target_path):
        continue
    
    fit_list = []
    date_folders = sorted(os.listdir(target_path))
    
    # 遍历日期文件夹
    for date in date_folders:
        date_path = os.path.join(target_path, date)
        if not os.path.isdir(date_path):
            continue
        
        # 遍历 FITS 文件
        fits_files = sorted(f for f in os.listdir(date_path) if f.endswith(".fit"))
        
        for fit_file in fits_files:
            
            #跳过B通道图像，只处理R通道
            if fit_file.find('_B_')>0:
                continue
            
            fit_list.append({
                "file_name": fit_file,
                "relative_path": f"{target}/{date}"
            })
    
    # 记录目标信息
    target_info = {
        "target_name": target,
        "observation_days": len(date_folders),
        "image_count": len(fit_list)
    }
    target_list.append(target_info)
    
    # 生成 FITS 图像列表 JSON
    fit_list_path = os.path.join(fit_list_dir, f"{target}.json")
    with open(fit_list_path, "w") as f:
        json.dump(fit_list, f, indent=4)

# 保存目标列表 JSON
with open(object_list_json, "w") as f:
    json.dump(target_list, f, indent=4)

print(f"目标列表已保存到 {object_list_json}")
print(f"各目标的 FITS 图像列表已保存到 {fit_list_dir}/")
